// Custom sorting plugin
(function($){$.fn.sorted=function(customOptions){var options={reversed:false,by:function(a){return a.text()}};$.extend(options, customOptions);$data=$(this);arr=$data.get();arr.sort(function(a, b){var valA = options.by($(a));var valB = options.by($(b));if(options.reversed){return (valA < valB) ? 1 : (valA > valB) ? -1 : 0}else{return (valA < valB) ? -1 : (valA > valB) ? 1 : 0}});return $(arr)}})(jQuery);

$(document).ready(function(){

	hist.init();
	compat.init();
	portfolio.init();
	project.init();
	
	if( !!window.prettyPrint )
		window.prettyPrint();
});

/** Let's make everything work **/
var compat = (function($){
	
	return {
		init : function(){
			console.log('Compatibility Initialization.');
		}
	}
})(jQuery);

/** Single Project Pages **/
var project = (function($){
	
	var v = {
		title : '',
		ajaxurl : '/wp-admin/admin-ajax.php',
		loader : '.loader',
		isAccessible : true,
		accessibleAttr: 'left',
		nav : '#project-nav',
		container : '#playpen',
		display : '.display',
		details : '.details',
		desc : '.description',
		tmpl : '#proj-tmpl',
		speed : 250,
		current : 0,
		currentID : 0,
		total : 0,
		activeClass : 'active'
	}
	
	/** Initial Setup **/
	function setupImageDetails(){
		console.log("Setting up Project Image Details");
		
		v.title = $('article header h1').first().text();
		v.contHeight = $(v.container).height();
		v.total = $('[data-action]', v.nav).length;
		v.current = $('li.active', v.nav).index();
		// Add the loader to the page
		$('<div class="'+v.loader.slice(1)+'" />').appendTo(v.nav).hide();
		
		// Set the height of the parent
		$( window ).load(function(){
			$(v.container).parent().height( v.contHeight );
		});
		
		// Switch the navigation active class to the anchor element
		$('li.'+v.activeClass, v.nav).removeClass(v.activeClass).children('a').addClass(v.activeClass);
	}
	
	function setupEvents(){
		// Nav thumbnail clicks
		$('body').delegate(v.nav+' a', 'click', function(e){
			getProjectItem(this);
			e.preventDefault();
		});
		
		// Arrow Keys
		$(window).keyup(function(e){
			switch( e.keyCode ){
				case 37 : previous(); break;
				case 39 : next(); break;
			}
		});
	}
	
	/** Initial history setup **/
	function setupHistoryEvents(){
		v.currentID = $('.display', v.container).data('id');
		
		// Replace the initial history state with the current, so we
		// can grab state data when the user goes back to the original
		hist.replace({
			id : v.currentID,
			title : $('.title', v.container).text(),
			desc : $('.description', v.container).html(),
			html : $('.display', v.container).html()
		}, window.title, window.location.href);
		
		hist.bind('statechange', function(){
			var state = hist.getState();
			updatePage(state.data);
		});
	}
	
	/** Go to the Next Item **/
	function next(){
		var next = (v.current+1 < v.total) ? v.current+1 : 0;
		getProjectItem( $('li:eq('+next+')', v.nav).children('a').first() );
	}
	
	/** Go to the Previous Item **/
	function previous(){
		var prev = (v.current-1 >= 0) ? v.current-1 : v.total-1;
		getProjectItem( $('li:eq('+prev+')', v.nav).children('a').first() );
	}
	
	/** Go grab the requested item **/
	function getProjectItem( element ){
		if( typeof element !== 'object' )
			return false;
		
		if( $(element).data('id') == v.currentID )
			return false;
		
		$.ajax({ 
			data : { action: $(element).data('action'), id: $(element).data('id'), href: $(element).data('href') },
			success : function(data){ success( data, element ) }
		});
	}
	
	/** If the request succeeded **/
	function success( data, element ){
		console.log("Successful ajax call");

		if( ! data.error && parseInt(data) != -1 ){
			hist.push( data, hist.formatTitle(data.title), $(element).prop('href') );
		}else{
			console.log( data );
		}
	}
	
	function updatePage( data ){	
		updateDisplay(data);
		updateNavigation(data.id, v.currentID);
	}
	
	/** Perform the DOM transformations and animations **/
	function updateDisplay( data ){	console.log(data);
		$(v.container)
			.parent().height(v.contHeight)
			.end().fadeOut( v.speed, function(){
				
				$(this).html( $(v.tmpl).tmpl(data) );

				if( $('img', this).length && ! $('img', this).prop('complete') ){
					$('img', this).last().load(function(e){ showContent() });
				}else{
					showContent();
				}
			});
	}
	
	function showContent(){
		v.contHeight = $(v.container).css('visibility', 'hidden').show().height();
		$(v.container)
			.hide().css('visibility', 'inherit')
			.parent().animate({height : v.contHeight}, v.speed )
			.end().fadeIn( Math.round( v.speed * 0.8, 0 ) );
	}
	
	function updateNavigation( newID, oldID ){
		findNavItem(oldID).removeClass(v.activeClass);
		findNavItem(newID).addClass(v.activeClass);
		v.current = findNavItem(newID).parent().index();
		v.currentID = newID;
	}
	
	function findNavItem( id ){ return $(v.nav).find('a[data-id="'+id+'"]') }
	
	function setupAjax(){
		$.ajaxSetup({ 
			url : v.ajaxurl, 
			timeout : 4000, 
			type : 'GET', 
			dataType : 'json' 
		});
		$(v.container)
			.ajaxError(ajaxError)
			.ajaxComplete(ajaxComplete)
			.ajaxSuccess(ajaxSuccess)
			.ajaxStart(ajaxStart)
			.ajaxStop(ajaxStop);
	}
	
	function ajaxError(event, xhr, settings, error){
		console.log('ajax error: '+error, event, xhr, settings);
	}
	
	function ajaxComplete(event, xmlhttp, settings){
		console.log('ajax complete', event, xmlhttp, settings);
	}
	
	function ajaxSuccess(event, xmlhttp, settings){
		console.log('ajax success', event, xmlhttp, settings);
	}
	
	function ajaxStart(){
		$(v.loader, v.nav).fadeIn('fast');
	}
	
	function ajaxStop(){
		$(v.loader, v.nav).fadeOut('fast');
	}

	return{
		init : function(obj){
			$.extend(v,obj);
			if( $(v.container).length ){
				console.log('Project Initialization');
				setupImageDetails();
				setupAjax();
				setupEvents();
				setupHistoryEvents();
			}
		}
	}
})(jQuery);

/** Portfolio Page **/
var portfolio = (function($){
	
	var v = {
		data : null,
		source : '#source',
		cats : '#sort-type',
		activeCat : null,
		date : '#sort-date',
		activeDate : null,
		activeClass : 'active'
	}
	
	function setupData(){
		v.activeCat = $('.active', v.cats);
		v.activeDate = $('.active', v.date);
		
		// If we're on the landing page, try to localize it
		if( $(v.source).hasClass('full') && Modernizr.localstorage ){
			v.data = $( v.source ).clone();
			localStorage.setItem('portfolio_items', v.data[0].outerHTML );
		}else{
			// Try to get all items for sorting
			if( Modernizr.localstorage && localStorage.getItem('portfolio_items') ){
				v.data = $( localStorage.getItem('portfolio_items') );
			}
		}
		
		// This forces the scrollbar so shifting doesn't happen
		$('html').css('overflowY', 'scroll');
		
		// Sort the data on click
		$(v.cats+' a').add( $(v.date+' a') ).click(function(e){
			
			var type = $(e.currentTarget).data('type');
			var sort = (type.indexOf('date') > -1) ? true : false;
			
			// Todo: Ajaxify this.
			if( ! Modernizr.localstorage )
				return true;
				
			hist.push({type:type, sort:sort}, hist.formatTitle( $(e.currentTarget).text().capitalize() ), $(e.currentTarget).attr('href') );
			
			e.preventDefault();
		});
	}
	
	function updateNavigation(type, sort){
		if( sort == true ){
			$(v.activeDate).removeClass(v.activeClass);
			v.activeDate = $(v.date+' a[data-type="'+type+'"]');
			$(v.activeDate).addClass(v.activeClass);
		}else{
			$(v.activeCat).removeClass(v.activeClass);
			v.activeCat = $(v.cats+' a[data-type="'+type+'"]');
			$(v.activeCat).addClass(v.activeClass);
		}
	}
	
	function updateDisplay(type, sort){
		
		updateNavigation(type, sort);
		
		var cat = $(v.activeCat);
		var order = $(v.activeDate).data('type');
		
		if( type == 'all' )
			filteredData = v.data.find('li');
		else
			filteredData = v.data.find('li[data-cats~="'+ $(cat).data('type') +'"]');
			
		filteredData = filteredData.sorted( {reversed: (order == 'date-asc') ? false : true, by: function(obj){ return $(obj).data('date') }} );
		
		$( v.source ).quicksand( filteredData );
	}
	
	function setupHistoryTracking(){
		hist.bind('statechange', function(){
			var state = hist.getState();
			updateDisplay(state.data.type, state.data.sort);
		});
	}
	
	return {
		init : function(){
			if( $('#projects').length ){
				setupData();
				setupHistoryTracking();
			}
		}
	}
})(jQuery);

// Object to track the visitors JS history
var hist = (function($){

	var v = {
		history : null,
		title : '',
	};
	
	function formatTitle( title ){
		
		return title + " | " + v.title;
	}
	
	return {
		bind : function(event, f){ return v.history.Adapter.bind(window, event, f) },
		getState : function(){ return v.history.getState() },
		push : function(data, title, url){ v.history.pushState(data, title, url) },
		replace : function(data, title, url){ v.history.replaceState(data, title, url) },
		back : function(){ v.history.back() },
		go : function(state){ v.history.go(state) },
		get : function(item){
			return eval("v."+item);
		},
		formatTitle : function(title){ return formatTitle(title) },
		init : function(){
			v.history = window.History;
			v.title = document.title;
		}
	}
})(jQuery);

// Custom Capitalize function
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}